package com.zee.activity

import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.TextView
import com.zee.utils.ZEventBusUtils
import com.zee.utils.ZLibrary
import com.github.mjdev.libaums.UsbMassStorageDevice
import android.util.Log
import com.github.mjdev.libaums.fs.FileSystem
import kotlinx.android.synthetic.main.activity_otg.*
import java.lang.StringBuilder


/**
 * 读写手机U盘
 */
class OTGFileActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ZLibrary.init(application, true);
        setContentView(R.layout.activity_otg)
        ZEventBusUtils.register(this)

        tv_save.setOnClickListener(View.OnClickListener {
            otgGet()
        }
        )
    }

    fun otgGet(): FileSystem? {
        val devices = UsbMassStorageDevice.getMassStorageDevices(this)
        var currentFs: FileSystem? = null
        for (device in devices) {//一般只有一个OTG借口，所以这里只取第一个
            try {
                device!!.init()
                //如果设备不支持一些格式的U盘，这里会有异常
                if (device == null || device.partitions == null ||
                        device.partitions[0] == null ||
                        device.partitions[0].fileSystem == null) {
                    return null
                }
                currentFs = device.partitions[0].fileSystem
                val stringBuilder = StringBuilder()
                stringBuilder.append("容量: " + currentFs!!.getCapacity())
                stringBuilder.append("已使用空间: " + currentFs!!.getOccupiedSpace())
                stringBuilder.append("剩余空间: " + currentFs!!.getFreeSpace())
                stringBuilder.append("block数目: " + currentFs!!.getChunkSize())
                tv_save.setText(stringBuilder)
            } catch (e: Exception) {
                return null
            }
        }
        return currentFs
    }

    override fun onDestroy() {
        super.onDestroy()

        ZEventBusUtils.unregister(this)
    }
}
